package com.example.onlinemonitoring.comCenter;
import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Dlzllsensor;
import com.example.onlinemonitoring.model.Dlzllhistory;
import com.example.onlinemonitoring.dao.DtssensorMapper;
import com.example.onlinemonitoring.dao.DtspartitionMapper;
import com.example.onlinemonitoring.model.Dtssensor;
import com.example.onlinemonitoring.model.Dtspartition;
import com.example.onlinemonitoring.model.Dlhlsepsensor;
import com.example.onlinemonitoring.model.common.MyResult;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.serviceImpl.DlhlsepsensorServiceImpl;
import com.example.onlinemonitoring.serviceImpl.DlzllsensorServiceImpl;
import com.example.onlinemonitoring.serviceImpl.YggxsensorServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/*这里beanName需要和数据库Appdevice中的simple对应并加上Com,不对应请自行修改
    例:simple:dlhl
    @Service("dlhlCom")
*/
@Service("dlzllCom")
@Scope("prototype")
public class DlzllCom extends CommPortManager {
        @Autowired
        private DlzllsensorServiceImpl dlzllsensorServiceImpl;
        @Autowired
        private DtspartitionMapper dtspartitionmapper;
        @Autowired
        private DtssensorMapper dtssensormapper;
        @Autowired
        private DlhlsepsensorServiceImpl dlhlsepsensorServiceImpl;

        @Override
        public void receiveData(String str) {
            try {
                str = str.toUpperCase();
                setText(str);
                //条件判断自己写
                reSend[addrindex] = 0;
                addrindex++;
                String addrstr = str.substring(0, 2);
                Integer addrint = parseHex4(addrstr);
                if (str.length()<12)
                return;
                float temperature=0;
                float currnet=0;
                float cdtemperature=0;

                // Dtssensor dts = new Dtssensor();
                // dts.setStationid(ad.getStationid());
                // dts.setIpaddr(ad.getIp());
                // dts.setChunk(addrint);
                // dts.setDevicegroup(ad.getDevicegroup());                
                // dts = dtssensormapper.selectsinglebytotal(dts);
                int iChunk = 0;
                // 分区循环开始
                Dtspartition dtsp = new Dtspartition();
                dtsp.setStationid(ad.getStationid());
                dtsp.setDevicegroup(ad.getDevicegroup());
                dtsp.setIpaddr(ad.getIp());
                //dtsp.setChunk(addrint);
                List<Dtspartition> dtspl = dtspartitionmapper.selectbytotal(dtsp);

                if (dtspl.size()== 0) {
                    setText("当前数据库组" + ad.getDevicegroup() + "无地址：" + addrint + " ！ 请先添加该地址！");
                    return;
                }
                for (int i = 0; i < dtspl.size(); i++) {
                    dtsp = dtspl.get(i);
                    if (dtsp == null) {
                        setText("当前数据库无监测点：设备地址" + addrint + "的监测点" + (i + 1) + " ！ 请先添加该监测点！");
                        return;
                    }
                    iChunk = dtsp.getChunk();
                    Dlhlsepsensor dlhlsensor = new Dlhlsepsensor();
                    //设置设备地址
                    dlhlsensor.setStationid(ad.getStationid());
                    dlhlsensor.setDevicegroup(ad.getDevicegroup());
                    dlhlsensor.setDeviceaddr(iChunk);
                    //查询对象
                    Dlhlsepsensor dlrecord = dlhlsepsensorServiceImpl.getModel(dlhlsensor);
                    if (dlrecord == null) {
                        setText("当前数据库无监测点：设备地址" + iChunk);
                        return;
                    }
                    currnet = isnull(dlrecord.getLastdcurrent());
                    
                    //if (dtsp.getInuse() == 0)
                    //    return;
                temperature =    isnull( dtsp.getMaximumtemp());
                    
                   
                Dlzllsensor dlzllsensor =  new Dlzllsensor();
                dlzllsensor.setStationid(ad.getStationid());
                dlzllsensor.setDevicegroup(ad.getDevicegroup());
                dlzllsensor.setDeviceaddr(iChunk);
                dlzllsensor.setPointaddr(dtsp.getPartitionno());
                //查询对象
                Dlzllsensor record = dlzllsensorServiceImpl.getModel(dlzllsensor);
                if (record == null) {
                    setText("当前数据库无监测点：设备地址" + iChunk);
                    return;
                }
                dlzllsensor.setLastdlhlcurrent(currnet);
                dlzllsensor.setLaststartcurrent(record.getLaststartcurrent());
                dlzllsensor.setLastairtemperature(record.getLastairtemperature());
                dlzllsensor.setLastskintemperature(temperature);
                //dlzllsensor.setLastcdtemperature(isnull(record.getLastcdtemperature()));
                cdtemperature = dlzllsensorServiceImpl.Calccurrent2(dlzllsensor); 
                //dlzllsensor.setLastcdtemperature(cdtemperature);
                dlzllsensor.setLaststarttemperature(cdtemperature);
                //dlzllsensor.setLasthisdatatime(record.getLasthisdatatime());
                AddAndUpdate(dlzllsensor,record);
                }


            } catch (Exception ex) {
                ex.printStackTrace();
                setText("从设备返回的数据有误！请检查串口！");
            }
        }

        @Transactional
        private void AddAndUpdate(Dlzllsensor sensor,Dlzllsensor record) {
            int alarmLevel = 0;// 报警等级
            String alarmMessage = "";// 报警消息
            //报警逻辑
            //这里写报警逻辑

            if(sensor.getLaststarttemperature()>90)
            {
                alarmLevel = 2;
                alarmMessage = "电缆芯温报警";
            }
            sensor.setLastalarmlevel(alarmLevel);
            sensor.setLastalarmmessage(alarmMessage);
            sensor.setLastcommunicationstatus(0);
            sensor.setLastdatatime(new Date());
            sensor.setLasthisdatatime(addHistory(record));
            if ( dlzllsensorServiceImpl.Update(sensor, false) == 0) {
                setText("更新实时数据失败，请检查数据库连接");
            }
        }
        private Date addHistory(Dlzllsensor sensor) {
            if (sensor != null) {
                if (sensor.getLasthisdatatime() == null) {
                    add(sensor);
                    return new Date();
                } else {
                    long lasttime = 0;
                    long nowtime = 0;
                    try {
                        lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                        nowtime = HexUtil.todate(new Date()).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    int timersp = 60000;
                    if (sensor.getLastalarmlevel() != 0) {
                        timersp = ad.getHisalarmtimersp()*1000;
                    } else {
                        timersp = ad.getHistimersp()*1000;
                    }
                    if (lasttime + timersp < nowtime) {
                        add(sensor);
                        return new Date();
                    }
                }
            }
            return null;
        }

        private void add(Dlzllsensor sensor) {
            Dlzllhistory his = new Dlzllhistory();
            his.setDeviceaddr(sensor.getDeviceaddr());
            his.setDevicegroup(sensor.getDevicegroup());
            his.setAlarmlevel(sensor.getLastalarmlevel());
            his.setAlarmmessage(sensor.getLastalarmmessage());
            his.setDatatime(sensor.getLastdatatime());
            his.setPointaddr(sensor.getPointaddr());
            his.setPointname(sensor.getPointname());
            his.setStationid(sensor.getStationid());
            //需要添加自己定义的属性
            his.setCurrentcarr(sensor.getLastcurrentcarr());
            his.setDlhlcurrent(sensor.getLastdlhlcurrent());
            his.setStartcurrent(sensor.getLaststartcurrent());
            his.setAirtemperature(sensor.getLastairtemperature());
            his.setSkintemperature(sensor.getLastskintemperature());
            his.setCdtemperature(sensor.getLaststarttemperature());
            //his.sets(sensor.getLastcdtemperature());
            dlzllsensorServiceImpl.Add(his);
        }


        @Async("threadPool")
        public void startSendThread(Appdevice Appdevice) throws Exception {
            checkType = "crc16";
            issend.put(Thread.currentThread().getId(), true);
            String cstr = "";
            String cmdtype = "";
            String nametype = "";
            int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
            while (issend.get(Thread.currentThread().getId()) != null) {
                if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                    addrindex = Appdevice.getAddrmin();
                cstr = String.format(Appdevice.getCmd(), String.format("%02X", addrindex));
                cstr = cstr + CRC16.calcCrc16(cstr);
                try {
                    Send(cstr);
                    receiveData(cstr);
                } catch (Exception EX) {
                     setText(EX.toString());
                }
                //setText("向" + Appdevice.getName() + "设备发送指令" + cstr);
                reSend[addrindex]++;
                if (reSend[addrindex] > 3) {
                dlzllsensorServiceImpl.UpdateStatus(ad, addrindex,1);
                reSend[addrindex] = 0;
                addrindex++;
                }
                Thread.sleep(timersp);
            }
        }

        // @Async("threadPool")
        // public void startReceiveThread(){
        //     isrecv.put(Thread.currentThread().getId(), true);
        //     while (isrecv.get(Thread.currentThread().getId()) != null) {
        //         //这里根据实际协议替换,解析方法recvCrc16;recvSum();
        //         recv();
        //         try {
        //             Thread.sleep(interval);
        //         } catch (InterruptedException e) {
        //             e.printStackTrace();
        //         }
        //     }
        // }
}
